const schedule = require('node-schedule');
const dict = {}
const axios = require('axios')
const {add, query, del} = require('./sqlApi')
const notify = require('./sendNotify');
Date.prototype.Format = function (fmt) {
    var e,
        n = this, d = fmt, l = {
            "M+": n.getMonth() + 1,
            "d+": n.getDate(),
            "D+": n.getDate(),
            "h+": n.getHours(),
            "H+": n.getHours(),
            "m+": n.getMinutes(),
            "s+": n.getSeconds(),
            "w+": n.getDay(),
            "q+": Math.floor((n.getMonth() + 3) / 3),
            "S+": n.getMilliseconds()
        };
    /(y+)/i.test(d) && (d = d.replace(RegExp.$1, "".concat(n.getFullYear()).substr(4 - RegExp.$1.length)));
    for (var k in l) {
        if (new RegExp("(".concat(k, ")")).test(d)) {
            var t, a = "S+" === k ? "000" : "00";
            d = d.replace(RegExp.$1, 1 == RegExp.$1.length ? l[k] : ("".concat(a) + l[k]).substr("".concat(l[k]).length))
        }
    }
    return d;
}

/**
 * 添加调度任务
 *
 * @param cron
 * @param url
 * @param insert
 * @returns {string}
 */
function startJob(cron, url, insert = true) {
    let names = url.split('/')
    let n = names[names.length - 1]
    if (n.indexOf("?") > -1) {
        n = n.split('?')[0]
    }
    if (dict[n]) {
        return 'scheduleJob fail job exist!!'
    }
    let job = schedule.scheduleJob(cron, () => {
        axios.get(url).then(
            async (e) => {
                let data = e.data
                let printf = ''
                if (typeof data == 'object') {
                    printf = JSON.stringify(data);
                } else {
                    printf = data
                }
                console.log(`${new Date().Format('yyyy-MM-dd hh:mm')} ==> ${printf}`)
                //是否要发送钉钉通知
                if (data.send) {
                    if (data.desc)
                        await notify.sendNotify(data.text, data.desc)
                }
            }
        ).catch(e => {
            console.log(`get ${url} error`)
        })

    });

    dict[n] = job
    console.log('scheduleJob ', n)
    if (insert) {
        add('schedule', [cron, url, n])
    }
    return 'scheduleJob ok'
}

/**
 * 根据任务名称 取消任务
 *
 * @param name
 */
function cancel(name) {
    dict[name].cancel();
    delete dict[name];
    console.log('cancel scheduleJob ', name)
    del('schedule', `name="${name}"`)
}

/**
 * 获取任务列表
 *
 * @returns {string}
 */
function list() {
    let arr = []
    for (let k in dict) {
        arr.push('job: ' + k)
    }
    if (arr.length > 0)
        return arr.join(',\n')
    else
        return 'no jobs'
}

/**
 * 启动时加载所有任务
 *
 * @returns {Promise<void>}
 */
async function loadAllJob() {
    let rows = await query('schedule')
    if (rows) {
        for (let r of rows) {
            startJob(r.cron, r.url, false)
        }
    }
}


/**
 * 添加调度任务
 *
 * @param cron
 * @param url
 * @param fo
 * @returns {string}
 */
function startBusinessJob(cron, url, format, senderId, global, api) {
    let token = global.getSession(senderId)
    let names = url.split('/')
    let n = names[names.length - 1]
    if (n.indexOf("?") > -1) {
        n = n.split('?')[0]
    }
    if (dict[n]) {
        return 'scheduleJob fail job exist!!'
    }
    let job = schedule.scheduleJob(cron, () => {
        console.log(`start ${url} ${token}`)
        axios.get(url, {
                headers: {
                    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
                    'Content-Type': 'application/json',
                    'auths_api': token
                },
            }
        ).then(
            async (e) => {
                try {
                    let data = e.data
                    let printf = ''
                    if (typeof data == 'object') {
                        printf = JSON.stringify(data);
                    } else {
                        printf = data
                    }
                    console.log(`${new Date().Format('yyyy-MM-dd hh:mm')} ==> ${printf}`)
                    //是否要发送钉钉通知
                    let returnData = data.returnData
                    let sendArr = [], s = ''
                    if (data.returnCode == 20011) {
                        //登陆过期
                        let p = global.getParams(token + '_login')
                        let newToken = await api.loginByUp(p);
                        global.setSession(senderId, newToken);
                        return

                    } else if (data.returnCode != 100) {
                        console.log(`${url} request error ... `)
                        return;
                    }
                    if (!format.push) {
                        //模板js
                        let js = new Function(`return ${format.js}`)()
                        let msg = js(returnData)
                        await notify.sendNotify(format.title, msg)
                    }

                } catch (e) {
                    console.log(e)
                }

            }
        ).catch(e => {
            console.log(`get ${url} error`)
        })


    });

    dict[n] = job
    console.log('scheduleJob ', n)

    return 'scheduleJob ok'
}


module.exports = {
    startJob, cancel, list, loadAllJob, startBusinessJob
}



